package com.zzl.myblog.View.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.zzl.myblog.Bean.ResponseBean.UserBean;
import com.zzl.myblog.MainActivity;
import com.zzl.myblog.R;
import com.zzl.myblog.Utils.HttpUtil;
import com.zzl.myblog.Utils.LogUtil;
import com.zzl.myblog.Utils.SaveAccount;
import com.zzl.myblog.Utils.responseUtility;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 用户登录
 *  1. 是否有缓存
 *   - 有，访问SharedPreferences,拿去用户数据，进行填充
 *   - 无，进入2
 *  2. 登录请求
 *   - 是否勾选保存用户名密码，若勾选，进行SharedPreferences保存
 *   - 发送请求到后端，进行登录验证
 *  3. 登录成功
 */
public class LoginActivity extends AppCompatActivity {
    static final String TAG = "LoginActivity";
    Map<String,String> userInfo;
    FloatingActionButton login,register;
    static Context context;
    EditText username_et,password_et;
    String username,password;
    private long lastClickBackTime = System.currentTimeMillis()- 3000; // 回退三秒时刻

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        context = getBaseContext();
        // 是否有缓存
        userInfo = SaveAccount.getUserInfo(this);
        // 初始化界面UI
        initUI();
    }

    private void initUI(){
        login = findViewById(R.id.fb_login);
        register = findViewById(R.id.fb_register);
        username_et= findViewById(R.id.et_user_number_login);
        password_et = findViewById(R.id.et_password_login);
        /*
        注意：若未缓存，则userInfo中各个字段值为null
         */
        username_et.setText(userInfo.get("username"));
        password_et.setText(userInfo.get("password"));
    }

    /**
     * 登录按钮
     */
    public void login(View view) {
        username = username_et.getText().toString().trim();
        password = password_et.getText().toString().trim();
        String url = "users";
        String params = "?username="+username+"&password="+password;
        HttpUtil.user_GET(url, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Looper.prepare();
                sendToast("登录失败");
                Looper.loop();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                        //拿到JSON格式的数据
                        String responseJson;
                        try {
                            responseJson = response.body().string();
                            //将返回的JSON数据-->user对象
                            final UserBean userBean =responseUtility.parse_user(responseJson);
                            if (userBean.getData() !=null) {
                                // 本地保存数据-文件存储
                                SaveAccount.saveAccountInfo(context, username, password);
                                // 转到MainActivity
                                Intent intent = new Intent(context, MainActivity.class);
                                intent.putExtra("username", username);
                                intent.putExtra("password", password);
                                startActivity(intent);
                                finish();
                            } else {
                                Looper.prepare();
                                sendToast("该账号未注册!");
                                Looper.loop();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

            }
        });
    }

    /**
     * 注册按钮
     */
    public void register(View view) {
        startActivity(new Intent(context, RegisterActivity.class));
    }

    /**
     * 首次back:提示用户再点击将会退出app
     * 再次点击：
     *    - 和上次间隔小于 2s ,则完全退出
     *    - 和上次间隔大于 2s , 又称为首次back，....
     */
    @Override
    public void onBackPressed() {
        if(System.currentTimeMillis()-lastClickBackTime > 2000){
            sendToast("再点击将会退出app");
            lastClickBackTime = System.currentTimeMillis();
        }else{
            System.exit(0);//完全退出  再次启动很慢
        }
    }

    private void sendToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
